package com.lin.socketio.event;

import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;
import com.lin.common.constant.CommonConstant;
import com.lin.common.constant.CustomerServiceConstant;
import com.lin.common.error.CustomRuntimeException;
import com.lin.common.utils.RedisSerializableUtils;
import com.lin.config.RequestUtils;
import com.lin.po.Chats;
import com.lin.po.Customer;
import com.lin.po.TranslateSetup;
import com.lin.properties.ConsumeProperties;
import com.lin.service.chats.ChatsService;
import com.lin.service.translate.TranslateService;
import com.lin.service.translatesetup.TranslateSetupService;
import com.lin.socketio.dto.ChatObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

@Component
public class ChatsNamespaceHandler implements SocketHandler {
    private static Logger log = LoggerFactory.getLogger(ChatsNamespaceHandler.class);

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    ConsumeProperties consumeProperties;

    @Value("${" + CustomerServiceConstant.socketio_topic + "}")
    private String socketio;

    @Value("${" + CustomerServiceConstant.content_topic + "}")
    private String content;

    @Autowired
    private ChatsService chatsService;

    @Autowired
    private TranslateService translateService;
    @Autowired
    private TranslateSetupService translateSetupService;

    @Override
    public void connect(SocketIOClient client, Customer c) {
    }

    public void event(SocketIOClient client, ChatObject data, AckRequest ackSender) throws CustomRuntimeException, UnsupportedEncodingException {
        log.info("send SocketIOClient:{}", client.getSessionId());
        log.info("handler send body :{}", data.toString());
        //撤销时会带ID过来 该分支不是撤销
        if(!StringUtils.equals(data.getReadFlag(), Chats.READ_FLAG_CANCEL)){
            /**
             * 由于该对象传输到各个消息消费应用中是时，他们都会对该对象进行存储，过需要先设置ID，用于只能存储一次；
             */
            data.setId(Long.parseLong(RedisSerializableUtils.generateForLong(CommonConstant.DEFAULT_LENGTH)));
            //只有内容为字符串的才是能翻译的
            if(StringUtils.equals(data.getContentType(),Chats.CONTENT_TYPE_STRING)){
                ////////////////查看是否有进行翻译的资格【购买翻译词量】////////////////////
                boolean flag=translateSetupService.translateFlag(data.getSender(),data.getContent().length());
                if(flag){
                    //TODO 如果设置翻译，则需要把发出的内容进行翻译，如果额度没有，则不允许翻译
                    translateService.translate(data);
                }
            }
            //异步更新群组的俩天信息和事件 用于后续查询对话是的最后一次显示。
            rabbitTemplate.convertAndSend(content, null, data);

        }else{//撤销
            data.setContent(data.getSender()+"撤回了一条信息。");
            chatsService.updateReadFlag(data);
        }
        /**
         * 发送消息到rabbitmq 为了做socket client做集群用。
         */
        rabbitTemplate.convertAndSend(socketio, null, data);

        if(!StringUtils.equals(data.getReadFlag(), Chats.READ_FLAG_CANCEL)){
            //保存出现错误也能继续发送
            try {
                chatsService.save(data);
            } catch (IOException e) {
                log.error("save ChatObject error", e);
            }
        }
        log.info("RabbitmqMQProducer send success");
    }

    @Override
    public void disconnect(SocketIOClient client) {

    }

}
